import os
import django

# 设置 Django 项目的配置
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings')
# 初始化 Django
django.setup()


def count_lines_in_file(file_path):
    """统计单个文件的代码行数（包括空行）"""
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()
        return sum(1 for line in lines if line.strip())  # 仅统计非空行

def count_code_lines_in_directory(directory):
    """递归统计目录中的所有Python文件的代码行数，但排除migrations目录，并按模块分类"""
    module_line_counts = {}
    total_lines = 0

    for root, dirs, files in os.walk(directory):
        # 跳过任何包含 'migrations' 的目录
        if 'migrations' in root.split(os.sep):
            continue

        # 获取模块名称（假设每个根目录下的文件夹为模块）
        module_name = os.path.relpath(root, directory).split(os.sep)[0]

        # 初始化模块行数
        if module_name not in module_line_counts:
            module_line_counts[module_name] = 0

        for file in files:
            if file.endswith('.py'):  # 仅统计Python文件
                file_path = os.path.join(root, file)
                lines_in_file = count_lines_in_file(file_path)
                module_line_counts[module_name] += lines_in_file
                total_lines += lines_in_file
                print(f"{file_path}: {lines_in_file} lines")

    # 输出模块行数
    print("\nModule line counts:")
    for module, lines in module_line_counts.items():
        print(f"{module}: {lines} lines")

    return total_lines


# 这个统计包括空行的可能有点问题
def count_lines_in_file_within_space(file_path):
    """统计单个文件的代码行数（包括空行）"""
    with open(file_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()
        return len(lines)  # 统计所有行，包括空行


def count_code_lines_in_directory_within_space(directory):
    """递归统计目录中的所有Python文件的代码行数，但排除migrations目录"""
    total_lines = 0
    for root, _, files in os.walk(directory):
        # 跳过任何包含 'migrations' 的目录
        if 'migrations' in root.split(os.sep):
            continue
        for file in files:
            if file.endswith('.py'):  # 仅统计Python文件
                file_path = os.path.join(root, file)
                lines_in_file = count_lines_in_file(file_path)
                total_lines += lines_in_file
                print(f"{file_path}: {lines_in_file} lines")
    return total_lines


project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # 假设该脚本位于scripts目录下
total_lines = count_code_lines_in_directory(project_root)
print(f"\nTotal lines of Python code without space in the project: {total_lines}")


# project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # 假设该脚本位于scripts目录下
# total_lines = count_code_lines_in_directory_within_space(project_root)
# print(f"\nTotal lines of Python code within space in the project: {total_lines}")
